#include "GLESAdaptor.h"
#include "RendererGLES.h"

namespace Nezha
{

	GLESAdaptor::GLESAdaptor()
		:mEngine(NULL)
	{

	}

	bool GLESAdaptor::initialize(NezhaEngine* engine)
	{
		// TODO create platform depend implementions

		mEngineCfg = (EngineConfig*)engine->_getInternalInterface("_NezhaEngine_Internal_Config");

		NZ_ASSERT(mEngineCfg);

		_initialize(engine);

		RendererGLES* renderer = NZ_New RendererGLES("Nezha opengl es 2.0 renderer");
		if(!renderer->_initialize(this))
		{
			return false;
		}

		return true;
	}

	void GLESAdaptor::uninitialize()
	{
		RendererGLES* renderer = static_cast<RendererGLES*>(Renderer::GetGlobal());
		renderer->_uninitialize();

		NZ_Delete renderer;
		// TODO

		_uninitialize();
	}

#ifdef NEZHA_OPENGL_ERROR_CHECK

	const char* GLESAdaptor::msErrorFileName = NULL;
	int GLESAdaptor::msErrorLine = 0;

	void GLESAdaptor::checkGLError()
	{
		int err = glGetError();
		if(err)
		{
			const char * errStr = "";
			switch(err)
			{
			case GL_INVALID_ENUM:
				errStr = "GL_INVALID_ENUM";
				break;
			case GL_INVALID_VALUE:
				errStr = "GL_INVALID_VALUE";
				break;
			case GL_INVALID_OPERATION:
				errStr = "GL_INVALID_OPERATION";
				break;
			case GL_OUT_OF_MEMORY:
				errStr = "GL_OUT_OF_MEMORY";
				break;
			}

			NZError("OpenGL ES2 error 0x%04X %s in func %s at line %i\n", err, errStr, msErrorFileName, msErrorLine);

		}
	}

#endif

	static GLESAdaptor* g_GLESApator = NULL;

	GLESAdaptor* GLESAdaptor::GetInstance()
	{
		return g_GLESApator;
	}

	extern "C" NEZHA_GLES_ENTRY SubsystemAdaptor* NezhaPluginCreate()
	{
		g_GLESApator = GLESAdaptor::CreateInstance();
		return g_GLESApator;
	}

	extern "C" void NEZHA_GLES_ENTRY NezhaPluginDestroy()
	{
		delete g_GLESApator;
		g_GLESApator = NULL;
	}

}//end namespace Nezha